// 获取DOM元素
const addFriendBtn = document.getElementById('add-friend-btn');
const addFriendModal = document.getElementById('add-friend-modal');
const closeModal = document.getElementById('add-friend-close-modal');
const submitBtn = document.getElementById('add-friend-submit-btn');
const friendIdInput = document.getElementById('add-friend-id');
const greetingInput = document.getElementById('add-friend-greeting');
const successMessage = document.getElementById('add-friend-success-message');

// 长按检测变量
let mouseDownTime = 0;
let isLongPress = false;

// 打开添加好友弹窗
addFriendBtn.addEventListener('click', function () {
    addFriendModal.classList.add('active');
    friendIdInput.focus();
});

// 关闭弹窗
function closeAddFriendModal() {
    addFriendModal.classList.remove('active');
    // 重置表单和状态
    friendIdInput.value = '';
    greetingInput.value = '你好，我是你的朋友，希望能加你为好友！';
    successMessage.style.display = 'none';
    submitBtn.style.display = 'block';
}

// 点击关闭按钮关闭弹窗
closeModal.addEventListener('click', closeAddFriendModal);

// 点击弹窗外部关闭弹窗（长按时不关闭）
addFriendModal.addEventListener('mousedown', function (e) {
    if (e.target === addFriendModal) {
        mouseDownTime = new Date().getTime();
        isLongPress = false;

        // 设置长按计时器
        setTimeout(() => {
            isLongPress = true;
        }, 300); // 300毫秒定义为长按
    }
});

addFriendModal.addEventListener('mouseup', function (e) {
    if (e.target === addFriendModal) {
        const currentTime = new Date().getTime();
        // 如果不是长按（短按），则关闭弹窗
        if (currentTime - mouseDownTime < 300 && !isLongPress) {
            closeAddFriendModal();
        }
    }
});

// ESC键关闭弹窗
document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape' && addFriendModal.classList.contains('active')) {
        closeAddFriendModal();
    }
});

// 提交好友请求
submitBtn.addEventListener('click', function () {
    const friendId = friendIdInput.value.trim();
    const greeting = greetingInput.value.trim();

    if (!friendId) {
        alert('请输入朋友ID');
        friendIdInput.focus();
        return;
    }

    sendAddFriendReq(friendId, greeting, localStorage.getItem("headPortrait"));

});

// 按Enter键提交表单
friendIdInput.addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
        submitBtn.click();
    }
});

greetingInput.addEventListener('keypress', function (e) {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        submitBtn.click();
    }
});
// 这里实现添加朋友的逻辑 先是发起请求
function sendAddFriendReq(friendId, content, headPortrait) {
    console.log("朋友id " + friendId);
    let userId = localStorage.getItem("userId");

    $.ajax({
        type: "post",
        url: "chat/tranFriendReq",
        contentType: "application/json",
        data: JSON.stringify({
            userId: userId,
            friendId: friendId,
            content: content,
        }),

        success: function (result) {
            let data = result.data;
            if (data.status != "fail") {
                setShowNotification("好友请求发送成功");
                // 隐藏弹窗
                $(".close-modal").click();
            } else {
                setShowNotification("请求发送失败 " + data.msg);
            }
        },

        error: function (err) {
            if (err.status == 406) {
                location.href = "login.html";
                return;
            }
            console.log(result.message);
        }
    });
}
